<?php
/**
 * V7
 * 
 * @author Leon
 *
 */
class data_user extends data {

	public function __construct () {
		parent::__construct();
	}
	/**
	 * 添加用户
	 * 
	 * @param String $type				// weibo / renren / kaixin001 / qqwb
	 * @param Int $social_id
	 * @param String $show_name		// 显示出来的名称，weibo对应的是screen_name，renren对应的是name，kaixin001对应的是name，qqwb对应的是nick
	 * @param String $action_name		// 微博@ 时跟随的名字，weibo对应的是screen_name，renren不需要，qqwb对应的是name
	 * @return int
	 */
	public function add_user_by_social_id ($type, $social_id, $show_name, $action_name) {
		$show_name = format_nickname($show_name);
		$show_name = ($show_name) ? $show_name : $social_id;			 // 没有show name就用id代替
		$action_name = format_nickname($action_name);
		$action_name = ($action_name) ? $action_name : $show_name;		// 没有action name 就用show name代替
		
		if ($type == 'weibo' and is_weibo_id($social_id) and !$this->one_by_social_id('weibo', $social_id)) {
			$insert_id = $this->db->execute('
					insert into
						users
					set
						nickname			= "' . $show_name . '",
						weibo_id			= "' . $social_id . '",
						weibo_actionname	= "'.$action_name.'"
			');
		} elseif ($type == 'renren' and is_renren_id($social_id) and !$this->one_by_social_id('renren', $social_id)) {
			$insert_id = $this->db->execute('
					insert into
						users
					set
						nickname			= "' . $show_name . '",
						renren_id			= "' . $social_id . '",
						renren_actionname	= "' . $action_name . '"
			');
		} elseif ($type == 'kaixin001' and is_kaixin001_id($social_id) and !$this->one_by_social_id('kaixin001', $social_id)) {
			$insert_id = $this->db->execute('
					insert into
						users
					set
						nickname			= "' . $show_name . '",
						kaixin001_id		= "' . $social_id . '",
						kaixin001_actionname	= "' . $action_name . '"
			');
		} elseif ($type == 'qqwb' and is_qqwb_id($social_id) and !$this->one_by_social_id('qqwb', $social_id)) {
			$insert_id = $this->db->execute('
					insert into
						users
					set
						nickname			= "' . $show_name . '",
						qqwb_id			= "' . $social_id . '",
						qqwb_actionname	= "' . $action_name . '",
						qqwb_showname		= "' . $show_name. '"
			');
		} else {
			new data_error_devel('创建新用户出错', array('type'=>$type, 'social_id'=>$social_id, 'show_name'=>$show_name, 'action_name'=>$action_name), __CLASS__, __FUNCTION__, __LINE__);
			return false;
		}
		
		if ($insert_id) {
			return $insert_id;
		} else return false;
	}
	/** 一个会员id的基本信息
	 *
	 * @param int $id        	
	 * @return Array
	 */
	public function one ($id) {
		$id = intval($id);
		if ($id) {
			$execute = $this->db->execute('
				select
					*
				from
					users
				where
					id = "' . $id . '"
			');
			if ($execute) {
				return $this->unserialize_token($execute[0]);
			} else return false;
		} else return false;
	}
	public function one_by_social_id ($type, $social_id) {
		if ($type === 'weibo' and is_weibo_id($social_id)) {
			$execute = $this->db->execute('
					select
						*
					from
						users
					where
						weibo_id = "' . $social_id . '"
					limit
						1
			');
		} elseif ($type === 'renren' and is_renren_id($social_id)) {
			$execute = $this->db->execute('
					select
						*
					from
						users
					where
						renren_id = "' . $social_id . '"
					limit
						1
			');
		} elseif ($type === 'kaixin001' and is_kaixin001_id($social_id)) {
			$execute = $this->db->execute('
					select
						*
					from
						users
					where
						kaixin001_id = "' . $social_id . '"
					limit
						1
			');
		} elseif ($type === 'qqwb' and is_qqwb_id($social_id)) {
			$execute = $this->db->execute('
					select
						*
					from
						users
					where
						qqwb_id = "' . $social_id . '"
					limit
						1
			');
		} else return false;
		
		if ($execute[0]) {
			return $this->unserialize_token($execute[0]);
		} else return false;
	}
	private function unserialize_token ($execute_0) {
		$execute_0['weibo_token']		= ($execute_0['weibo_token'])				? unserialize($execute_0['weibo_token'])		: '';
		$execute_0['weibo_token']		= isset($execute_0['weibo_token']['access_token'])		? $execute_0['weibo_token']				: '';
		$execute_0['renren_token']		= ($execute_0['renren_token'])				? unserialize($execute_0['renren_token'])		: '';
		$execute_0['renren_token']		= isset($execute_0['renren_token']['access_token'])		? $execute_0['renren_token']				: '';
		$execute_0['kaixin001_token']           = ($execute_0['kaixin001_token'])				? unserialize($execute_0['kaixin001_token'])	: '';
		$execute_0['kaixin001_token']           = isset($execute_0['kaixin001_token']['access_token'])	? $execute_0['kaixin001_token']			: '';
		$execute_0['qqwb_token']		= ($execute_0['qqwb_token'])					? unserialize($execute_0['qqwb_token'])		: '';
		$execute_0['qqwb_token']		= isset($execute_0['qqwb_token']['access_token'])		? $execute_0['qqwb_token']				: '';
		return $execute_0;
	}
	public function social_id_to_uid ($type, $social_id) {
		if ($type === 'weibo' and is_weibo_id($social_id)) {
			$execute = $this->db->execute('select id from users where weibo_id		= "' . $social_id . '" limit 1');
		} elseif ($type === 'renren' and is_renren_id($social_id)) {
			$execute = $this->db->execute('select id from users where renren_id		= "' . $social_id . '" limit 1');
		} elseif ($type === 'kaixin001' and is_kaixin001_id($social_id)) {
			$execute = $this->db->execute('select id from users where kaixin001_id	= "' . $social_id . '" limit 1');
		} elseif ($type === 'qqwb' and is_qqwb_id($social_id)) {
			$execute = $this->db->execute('select id from users where qqwb_id		= "' . $social_id . '" limit 1');
		} else return false;
		
		if ($execute[0]['id']) {
			return $execute[0]['id'];
		} else 	return false;
	}
	/**
	 * 合并用户
	 * 
	 * @param type $uid
	 * @param type $social_type
	 * @param type $token			//   (uid, access_token, refresh_token, ctime, expires_in, name, nick)
	 * @return boolean
	 */
	public function merge_user ($uid, $social_type, $token) {
		$uid = intval($uid);
		if ($uid and $social_type and $token) {
			// 检查token的用户是否是已注册用户
			if ($social_type === 'weibo' and is_weibo_id($token['uid'])) {
				$del_user = $this->db->execute('select * from users where weibo_id		= "' . $token['uid'] . '" limit 1');
			} elseif ($social_type === 'renren' and is_renren_id($token['uid'])) {
				$del_user = $this->db->execute('select * from users where renren_id		= "' . $token['uid'] . '" limit 1');
			} elseif ($social_type === 'kaixin001' and is_kaixin001_id($token['uid'])) {
				$del_user = $this->db->execute('select * from users where kaixin001_id		= "' . $token['uid'] . '" limit 1');
			} elseif ($social_type === 'qqwb' and is_qqwb_id($token['uid'])) {
				$del_user = $this->db->execute('select * from users where qqwb_id		= "' . $token['uid'] . '" limit 1');
			}
			
			if ($del_user[0]) {		// 已经是注册用户
				$del_user = $del_user[0];
				if ($uid <> $del_user['id']) {
					// 用del user中的字段把current user中空缺的部分补齐
					$current_user = $this->db->execute('select * from users where id = '.$uid);
					$current_user = $current_user[0];
					$sql = '';
					if ($del_user['weibo_id'] and !$current_user['weibo_id']) {
						$sql .= " weibo_id = '".$del_user['weibo_id']."', weibo_actionname = '".addslashes($del_user['weibo_actionname'])."', weibo_token ='".$del_user['weibo_token']."',";
					}
					if ($del_user['renren_id'] and !$current_user['renren_id']) {
						$sql .= " renren_id = '".$del_user['renren_id']."', renren_actionname = '".addslashes($del_user['renren_actionname'])."', renren_token ='".$del_user['renren_token']."',";
					}
					if ($del_user['kaixin001_id'] and !$current_user['kaixin001_id']) {
						$sql .= " kaixin001_id = '".$del_user['kaixin001_id']."', kaixin001_actionname = '".addslashes($del_user['kaixin001_actionname'])."', kaixin001_token ='".$del_user['kaixin001_token']."',";
					}
					if ($del_user['qqwb_id'] and !$current_user['qqwb_id']) {
						$sql .= " qqwb_id = '".$del_user['qqwb_id']."', qqwb_actionname = '".addslashes($del_user['qqwb_actionname'])."', qqwb_showname = '".addslashes($del_user['qqwb_showname'])."', qqwb_token ='".$del_user['qqwb_token']."',";
					}
					
					// 删除del users
					$this->db->execute('delete from users where id = "'.$del_user['id'].'"');
					
					// 注意：先删除del user，然后再复制数据到current user，否则由于表结构中social id是unique，social id会重复而导致SQL失败
					if ($sql) {
						$sql = "update users set " . substr($sql, 0, -1) . " where id = " . $uid ;
						$this->db->execute($sql);
					}
					
					// 把token写到users表中给uid
					$data_social = new data_social();
					if ($data_social->save_token_by_uid($uid, $social_type, $token)) {
						// 发布Event
						new data_event('merge_user', array('user_id'=>$uid, 'del_uid'=>$del_user['id']), 'high');
						return true;
					} else {
						new data_error_devel('合并账号时，save token 出错', array('uid'=>$uid, 'del_user'=>$del_user, 'social_type'=>$social_type, 'token'=>$token), __CLASS__, __FUNCTION__, __LINE__);
						return false;
					}
				} else {
					new data_error_devel('合并账号时，两个id怎么能一样呢？', array('uid'=>$uid, 'del_user'=>$del_user, 'social_type'=>$social_type, 'token'=>$token), __CLASS__, __FUNCTION__, __LINE__);
					return true;
				}
			} else {			// 不是注册用户
				// 把token写到users表中给uid
				$data_social = new data_social();
				$return = $data_social->save_token_by_uid($uid, $social_type, $token);
				// 发布event，更新好友
				new data_event('update_friends', array('user_id'=>$uid), 'high');
				return $return ;
			}
		} else return false;
	}
	public function merge_user_by_event ($uid, $del_uid) {
		$uid		= intval($uid);
		$del_uid	= intval($del_uid);
		if ($uid and $del_uid) {
			// save_article
			$this->db->execute('update save_article set user_id = ' . $uid . ' where user_id = ' . $del_uid);
			// save_article_del
			$this->db->execute('update save_article_del set user_id = ' . $uid . ' where user_id = ' . $del_uid);
			// home_hot
			$this->db->execute('update home_hot set user_id = "'.$uid.'" where user_id = "'.$del_uid.'"');
			$this->db->execute('update home_hot set receiver_id = "'.$uid.'" where receiver_id = "'.$del_uid.'"');
			// circle_article
			$this->db->execute('update circle_article set author_id = "'.$uid.'" where author_id = "'.$del_uid.'"');
			// circle_member得一个一个检查，同时修改了circle表中的total_member和total_follower
			$this->merge_circle_member($uid, $del_uid);
			// friend表也不能简单的update，也得检查是否有重复的，合并recommend统计数
			$this->merge_friend($uid, $del_uid);
			// recommend_article直接用ignore修改，重复会被剩下，然后把剩下的删除
			$this->merge_recommend($uid, $del_uid);
			// feed直接用ignore修改，重复会被剩下，然后把剩下的删除
			$this->merge_feed($uid, $del_uid);
			// cache_social
			$this->db->execute('update cache_social set user_id = "'.$uid.'" where user_id = "'.$del_uid.'"');
			return true;
		} else return false;
	}
	private function merge_feed ($uid, $del_uid) {
		$this->db->execute('update ignore feed set sender_id   = "'.$uid.'" where sender_id   = "'.$del_uid.'"');
		$this->db->execute('update ignore feed set receiver_id = "'.$uid.'" where receiver_id = "'.$del_uid.'"');
		$this->db->execute('delete from feed where sender_id = "'.$del_uid.'" or receiver_id = "'.$del_uid.'"');
	}
	private function merge_recommend ($uid, $del_uid) {
		$this->db->execute('update ignore recommend_article set sender_id = ' . $uid . ' where sender_id = ' . $del_uid);
		$this->db->execute('update ignore recommend_article set receiver_id = ' . $uid . ' where receiver_id = ' . $del_uid);
		$this->db->execute('delete from recommend_article where sender_id = "'.$del_uid.'" or receiver_id = "'.$del_uid.'"');
	}
	private function merge_friend ($uid, $del_uid) {
		// 查询出del friend中与user friend重合的部分
		$same_in_del = $this->db->execute('
			select 
				*
			from 
				friends 
			where 
				user_id = '.$del_uid.' and 
				friend_id IN (
					select friend_id from friends where user_id = '.$uid.'
				)
		');
		if (is_array($same_in_del)) {
			foreach ($same_in_del as $del) {
				// 给“我”增加recommend统计数
				$this->db->execute('
					update 
						friends 
					set 
						total_recommends_send	= total_recommends_send	+ ' . $del['total_recommends_send'] . ', 
						total_recommends_receive	= total_recommends_receive	+ ' . $del['total_recommends_receive'] . '
					where
						user_id	= '.$uid.'			and
						friend_id	= '.$del['friend_id'].'
				');
				// 给“我的好友”增加recommend统计数
				$this->db->execute('
					update 
						friends 
					set 
						total_recommends_send	= total_recommends_send	+ ' . $del['total_recommends_receive'] . ', 
						total_recommends_receive	= total_recommends_receive	+ ' . $del['total_recommends_send'] . '
					where
						user_id	= '.$del['friend_id'].'	and
						friend_id	= '.$uid.'
				');
				// 删除del双方的friend记录
				$this->db->execute('delete from friends where id = '. $del['id']);
				$this->db->execute('delete from friends where user_id = '.$del['friend_id'].' and friend_id = '.$del['user_id']);
			}
		}
		// 不重复的直接修改就行了
		$this->db->execute('update friend set user_id    = ' . $uid . ' where user_id    = '.$del_uid);
		$this->db->execute('update friend set friend_id = ' . $uid . ' where friend_id = ' . $del_uid);
	}
	private function merge_circle_member ($uid, $del_uid) {
		// 查询出del user的circle与user的circle相互重合的部分
		$same_in_del = $this->db->execute('
			select 
				u.id				AS u_id,
				u.user_id			AS u_uid,
				u.type			AS u_type,
				u.total_articles_by_me	AS u_total,
				u.circle_id			AS circle_id,
				d.id				AS d_id,
				d.user_id			AS d_uid,
				d.type			AS d_type,
				d.total_articles_by_me	AS d_total
			from 
				circle_member AS u,
				circle_member AS d
			where 
				u.user_id	= '.$uid.'		and
				d.user_id	= '.$del_uid.'	and
				u.circle_id	= d.circle_id
		');
		if (is_array($same_in_del)) {
			// 把member type字符串对应成数字
			$type_to_number = array (
				'follower'	=> 1,
				'member'	=> 2,
				'admin'	=> 3,
				'founder'	=> 4,
			);
			foreach ($same_in_del as $v) {
				// 如果将要删除的成员权限更高，那么升级权限，修改circle成员统计数，最后删除该条
				if ( $type_to_number[$v['d_type']] > $type_to_number[$v['u_type']] ) {		// 升级、同时合并统计数
					$this->db->execute('
						update 
							circle_member 
						set 
							type				= "'.$v['d_type'].'",
							total_articles_by_me	= total_articles_by_me + '.$v['d_total'].'	
						where 
							id = "'.$v['u_id'].'" 
					');
				} else {		// 不用升级，只合并统计数
					$this->db->execute('
						update 
							circle_member 
						set 
							total_articles_by_me	= total_articles_by_me + '.$v['d_total'].'	
						where 
							id = "'.$v['u_id'].'" 
					');
				}
				// 最后删除del user的记录
				$this->db->execute('delete from circle_member where id = ' . $v['d_id']);
			}
		}
		// 其余不重复的就直接修改了
		$this->db->execute('update circle_member set user_id = ' . $uid . ' where user_id = '.$del_uid);
	}
	private function update_me_info ($me) {
		if ($me['weibo_id'] and $me['weibo_token']['access_token']) {
			$data_weibo = new data_weibo();
			$weibo = $data_weibo->get_user_info($me['weibo_id'], $me['weibo_token']['access_token']);		// (id, screen_name, name ...)
			if ($weibo['screen_name']) {
				$set[] = ' weibo_actionname = "'.addslashes($weibo['screen_name']).'" ';
			} 
		}
		if ($me['renren_id'] and $me['renren_token']['access_token']) {
			$data_renren = new data_renren();
			$renren = $data_renren->get_user_info($me['renren_token']['access_token']);				// (uid, name ...)
			if ($renren['name']) {
				$set[] = ' renren_actionname = "'.addslashes($renren['name']).'" ';
			} 
		}
		if ($me['kaixin001_id'] and $me['kaixin001_token']['access_token']) {
			$data_kaixin001 = new data_kaixin001();
			$kaixin001 = $data_kaixin001->get_me_info($me['kaixin001_token']['access_token']);		// (uid, name)
			if ($kaixin001['name']) {
				$set[] = ' kaixin001_actionname = "'.addslashes($kaixin001['name']).'" ';
			} 
		}
		if ($me['qqwb_id'] and $me['qqwb_token']['access_token']) {
			$data_qqwb = new data_qqwb();
			$qqwb = $data_qqwb->get_user_info($me['qqwb_token']['access_token'], $me['qqwb_token']['uid']);		// (openid, name, nick)
			if ($qqwb['name'] and $qqwb['nick']) {
				$set[] = ' qqwb_actionname = "'.addslashes($qqwb['name']).'" ';
				$set[] = ' qqwb_showname = "'.addslashes($qqwb['nick']).'" ';
			}
		}
		
		if (is_array($set)) {
			return $this->db->execute('
				update
					users
				set
					' . implode(' , ', $set) . '
				where
					id = "'.$me['id'].'"
			');
		} else return false;
	}

	public function update_friends_by_event ($user_id) {
		$user_id = intval($user_id);
		$user = $this->one($user_id);
		// 读出我当前的好友，按微博id整理成数组
		$data_friend = new data_friend();
		$friends = $data_friend->ls($user_id, 'all', 'all', 1, 0);				// ((weibo_id,renren_id,kaixin001_id, qqwb_id...),...)
		if ($user) {
			// 更新我的个人社交账号信息
			$this->update_me_info($user);
			
			// 检查微博
			$insite_friends = $outsite_friends = '';				// 初始化临时变量
			if ($user['weibo_token']['access_token']) {				// 是微博登陆用户
				$data_weibo = new data_weibo();
				$outsite_friends = $data_weibo->get_friends($user_id);		// 在cache中读取
				if (!$outsite_friends) {								// 如果cache过期(默认6小时)或者尚未建立，那么去api读好友，然后进行更新
					$outsite_friends = $data_weibo->get_friends($user_id, $user['weibo_token']);		// 去微博api读出好友 array ( (weibo_id, nickname), ...... )
					if (is_array($outsite_friends)) {										// 如果成功读出了好友
						if (is_array($friends)) {
							foreach ($friends as $v) {
								if ($v['weibo_id']) $insite_friends[] = $v['weibo_id'];				// 在服务器上的好友中摘出微博用户
							}
						}
						$this->update_friends_by_weibo($user_id, $insite_friends, $outsite_friends);
					}
				}
			}
			// 检查人人
			$insite_friends = $outsite_friends = '';			// 清除临时变量
			if ($user['renren_token']['access_token']) {				// 是人人网登陆用户
				$data_renren = new data_renren();
				$outsite_friends = $data_renren->get_friends($user_id);	// 在cache中读取
				if (!$outsite_friends) {							// 如果cache过期(默认6小时)或者尚未建立，那么去api读好友，然后进行更新
					$outsite_friends = $data_renren->get_friends($user_id, $user['renren_token']);	// 去人人api读出好友 array ( (renren_id, nickname), ...... )
					if (is_array($outsite_friends)) {										// 如果成功读出了好友
						if (is_array($friends)) {
							foreach ($friends as $v) {
								if ($v['renren_id']) $insite_friends[] = $v['renren_id'];				// 在服务器上的好友中摘出人人用户
							}
						}
						$this->update_friends_by_renren($user_id, $insite_friends, $outsite_friends);
					}
				}
			}
			// 检查开心网
			$insite_friends = $outsite_friends = '';			// 清除临时变量
			if ($user['kaixin001_token']['access_token']) {				// 是开心001登陆用户
				$data_kaixin001 = new data_kaixin001();
				$outsite_friends = $data_kaixin001->get_friends($user_id);	// 在cache中读取
				if (!$outsite_friends) {							// 如果cache过期(默认6小时)或者尚未建立，那么去api读好友，然后进行更新
					$outsite_friends = $data_kaixin001->get_friends($user_id, $user['kaixin001_token']);	// 去人人api读出好友 array ( (kaixin001_id, name), ...... )
					if (is_array($outsite_friends)) {										// 如果成功读出了好友
						if (is_array($friends)) {
							foreach ($friends as $v) {
								if ($v['kaixin001_id']) $insite_friends[] = $v['kaixin001_id'];				// 在服务器上的好友中摘出人人用户
							}
						}
						$this->update_friends_by_kaixin001($user_id, $insite_friends, $outsite_friends);
					}
				}
			}
			// 检查腾讯微博
			$insite_friends = $outsite_friends = '';			// 清除临时变量
			if ($user['qqwb_token']['access_token']) {				// 是人人网登陆用户
				$data_qqwb = new data_qqwb();
				$outsite_friends = $data_qqwb->get_friends($user_id);	// 在cache中读取
				if (!$outsite_friends) {							// 如果cache过期(默认6小时)或者尚未建立，那么去api读好友，然后进行更新
					$outsite_friends = $data_qqwb->get_friends($user_id, $user['qqwb_token']);	// 去腾讯api读出好友 array ( (qqwb_id, nickname, name), ...... )
					if (is_array($outsite_friends)) {										// 如果成功读出了好友
						if (is_array($friends)) {
							foreach ($friends as $v) {
								if ($v['qqwb_id']) $insite_friends[] = $v['qqwb_id'];				// 在服务器上的好友中摘出腾讯微博用户
							}
						}
						$this->update_friends_by_qqwb($user_id, $insite_friends, $outsite_friends);
					}
				}
			}
			return true;
		} else return false;
	}
	private function update_friends_by_weibo ($user_id, $insite_friends, $outsite_friends) {
		$insite_friends = (empty($insite_friends)) ? array() : $insite_friends;
		// 检查每个互粉好友是否在我的当前好友名单中
		foreach ($outsite_friends as $v) {
			if (array_search($v['weibo_id'], $insite_friends) === false) {			// 不在insite名单中
				// 检查是否是注册用户
				$data_friend = new data_friend();
				$friend_id = $this->social_id_to_uid('weibo', $v['weibo_id']);
				if ($friend_id) {
					// 已经是注册用户，但是不是好友，然后把双方加为好友
					$data_friend->add($user_id, $friend_id);
				} else {
					// 不是注册用户，那么就注册新用户，然后把双方加为好友
					$insert_id = $this->add_user_by_social_id('weibo', $v['weibo_id'], $v['nickname'], $v['nickname']);
					$data_friend->add($user_id, $insert_id);
				}
			} else {
				// 已经在好友名单中，无需操作
			}
			// 更新每个人的微博screen name，以保证名称的正确，这样才能正确的构造发布微博时的@xxx
			$v['nickname'] = ($v['nickname']) ? $v['nickname'] : $v['weibo_id'];		// 如果没有nickname，就用weibo id来代替
			$this->db->execute('
				update
					users
				set
					weibo_actionname = "'.  addslashes($v['nickname']).'"
				where
					weibo_id		= "'.$v['weibo_id'].'"
			');
		}
	}
	private function update_friends_by_renren ($user_id, $insite_friends, $outsite_friends) {
		$insite_friends = (empty($insite_friends)) ? array() : $insite_friends;
		// 检查每个互粉好友是否在我的当前好友名单中
		foreach ($outsite_friends as $v) {
			if (array_search($v['renren_id'], $insite_friends) === false) {			// 不在insite名单中
				// 检查是否是注册用户
				$data_friend = new data_friend();
				$friend_id = $this->social_id_to_uid('renren', $v['renren_id']);
				if ($friend_id) {
					// 已经是注册用户，但是不是好友，把双方加为好友
					$data_friend->add($user_id, $friend_id);
				} else {
					// 不是注册用户，那么就注册新用户，然后把双方加为好友
					$insert_id = $this->add_user_by_social_id('renren', $v['renren_id'], $v['nickname'], $v['nickname']);
					$data_friend->add($user_id, $insert_id);
				}
			} else {
				// 已经在好友名单中，无需操作
			}
			// 更新每个人的nickname，以保证名称的正确，这样才能正确的构造发布时的@xxx
			$v['nickname'] = ($v['nickname']) ? $v['nickname'] : $v['renren_id'];		// 如果没有nickname，就用renren_id来代替
			$this->db->execute('
				update
					users
				set
					renren_actionname = "'.  addslashes($v['nickname']).'"
				where
					renren_id		= "'.$v['renren_id'].'"
			');
		}
	}
	private function update_friends_by_kaixin001 ($user_id, $insite_friends, $outsite_friends) {
		$insite_friends = (empty($insite_friends)) ? array() : $insite_friends;
		// 检查每个互粉好友是否在我的当前好友名单中
		foreach ($outsite_friends as $v) {
			if (array_search($v['kaixin001_id'], $insite_friends) === false) {			// 不在insite名单中
				// 检查是否是注册用户
				$data_friend = new data_friend();
				$friend_id = $this->social_id_to_uid('kaixin001', $v['kaixin001_id']);
				if ($friend_id) {
					// 已经是注册用户，但是不是好友，把双方加为好友
					$data_friend->add($user_id, $friend_id);
				} else {
					// 不是注册用户，那么就注册新用户，然后把双方加为好友
					$insert_id = $this->add_user_by_social_id('kaixin001', $v['kaixin001_id'], $v['name'], $v['name']);
					$data_friend->add($user_id, $insert_id);
				}
			} else {
				// 已经在好友名单中，无需操作
			}
			// 更新每个人的name，以保证名称的正确。不过开心001构造@的时候，并不需要name，是用kaixin001_id来构造的
			$v['name'] = ($v['name']) ? $v['name'] : $v['kaixin001_id'];		// 如果没有name，就用kaixin001_id来代替
			$this->db->execute('
				update
					users
				set
					kaixin001_actionname = "'.  addslashes($v['name']).'"
				where
					kaixin001_id		= "'.$v['kaixin001_id'].'"
			');
		}
	}
	private function update_friends_by_qqwb ($user_id, $insite_friends, $outsite_friends) {
		$insite_friends = (empty($insite_friends)) ? array() : $insite_friends;
		// 检查每个互粉好友是否在我的当前好友名单中
		foreach ($outsite_friends as $v) {
			if (array_search($v['qqwb_id'], $insite_friends) === false) {			// 不在insite名单中
				// 检查是否是注册用户
				$data_friend = new data_friend();
				$friend_id = $this->social_id_to_uid('qqwb', $v['qqwb_id']);
				if ($friend_id) {
					// 已经是注册用户，但是不是好友，把双方加为好友
					$data_friend->add($user_id, $friend_id);
				} else {
					// 不是注册用户，那么就注册新用户，然后把双方加为好友
					$insert_id = $this->add_user_by_social_id('qqwb', $v['qqwb_id'], $v['nick'], $v['name']);
					$data_friend->add($user_id, $insert_id);
				}
			} else {
				// 已经在好友名单中，无需操作
			}
			// 更新每个人的action name，以保证名称的正确，这样才能正确的构造发布微博时的@xxx
			$this->db->execute('
				update
					users
				set
					qqwb_actionname = "'.  addslashes($v['name']).'",
					qqwb_showname = "'.  addslashes($v['nick']).'"
				where
					qqwb_id		= "'.$v['qqwb_id'].'"
			');
		}
	}
	
	public function publish_social_msg_by_event_on_save_article ($uid, $article_id, $checked_friends) {
		$uid				= intval($uid);
		$article_id			= intval($article_id);
		$data_save_article	= new data_save_article();
		$article			= $data_save_article->one($uid, $article_id);
		$is_public			= $data_save_article->is_public($article_id);
		$checked_friends		= format_id_string($checked_friends, FALSE);	// 返回字符串
		// 查询出所有被推荐者的信息
		$friends_info = $this->db->execute('
			select
				*
			from
				users
			where
				id IN ('.$checked_friends.')
		');
		
		if ($is_public and $article and is_array($friends_info)) {
			$user = $this->one($uid);
			// 检查是否存在微博账号，如果存在并且有被推荐的微博好友，则发布微博
			if ($user['weibo_token']['access_token']) {
				$this->publish_by_weibo($friends_info, $user['weibo_token']['access_token'], $article_id, $article['title']);
			}
			// 检查是否存在人人账号，如果存在并且有被推荐的人人好友，则发布信息
			if ($user['renren_token']['access_token']) {
				$this->publish_by_renren($friends_info, $user['renren_token']['access_token'], $article_id);
			}
			// 检查kaixin001的用户
			if ($user['kaixin001_token']['access_token']) {
				$this->publish_by_kaixin001($friends_info, $user['kaixin001_token']['access_token'], $article_id, $article['title']);
			}
			// 检查是否存在腾讯微博账号，如果存在并且有被推荐的腾讯微博好友，则发布微博
			if ($user['qqwb_token']['access_token']) {
				$this->publish_by_qqwb($friends_info, $user['qqwb_token']['uid'], $user['qqwb_token']['access_token'], $article_id, $article['title']);
			}
		}
	}
	private function publish_by_weibo ($friends, $access_token, $article_id, $article_title) {
		// 把微博用户都摘出来
		foreach ($friends as $v) {
			if ($v['weibo_id'] and $v['weibo_actionname']) {
				$weibo_friends[] = $v['weibo_actionname'];
			}
		}
		// 如果存在微博好友
		if (is_array($weibo_friends)) {
			$data_weibo = new data_weibo();
			// 构造微博正文
			$msg = array();
			$msg_head = '推荐：《';
			$msg_foot = '》'. $data_weibo->shorturl('http://uread.me/?ureadmer='.  data_social::make_recommend_id('weibo', $article_id), $access_token). ' ';
			$tmp = $msg_head . $article_title . $msg_foot;
			// 微博正文的字符别超过140字，如果超过则截短title
			if (mb_strlen($tmp) > 140) {
				$tmp = $msg_head . mb_substr($article_title, 0, (140 - mb_strlen($msg_head) - mb_strlen($msg_foot))) . $msg_foot;
				$msg[0] = $tmp;
				$tmp = '';		// 清空tmp
			}
			$i = sizeof($msg);
			foreach ($weibo_friends as $v) {
				$tmp .= '@' . $v;				// 在tmp后面累加
				if (mb_strlen($tmp) < 140) {		// 长度小于140，把@screen_name真正写入$msg数组中
					$msg[$i]	= $tmp;
				} else {					// 长度超了，那就把tmp清空重写，然后写入到$msg数组的下一个记录中
					$i++;
					$tmp		= '@' . $v;
					$msg[$i]	= $tmp;
				}
				if ($i>2) break;				// 太多的@就忽略了，测试了新浪微博只能评论两次，多了发不出去
			}
			// msg的第一条是正文，第2、3条是评论
			if (is_array($msg)) {
				$update = $data_weibo->post($msg[0], $access_token);		// 发布微博
				if ($update['id']) {									// 发布微博成功
					if ($msg[1]) {
						$data_weibo->recomment($update['id'], $msg[1], $access_token);	// 只发布两条评论，再多的话，微博api就会返回post too fast错误
					}
					if ($msg[2]) {
						$data_weibo->recomment($update['id'], $msg[2], $access_token);	// 只发布两条评论，再多的话，微博api就会返回post too fast错误
					}
					return true;
				} else return false;
			} else return false;
		} else return false;
	}
	private function publish_by_renren ($friends, $access_token, $article_id) {
		// 用昵称来构造人人feed的@
		$at = '推荐： ';
		// 把人人用户摘出来
		foreach ($friends as $v) {
			if ($v['renren_id'] and $v['renren_actionname']) {
				$at	.= '@'.$v['renren_actionname'].'('.$v['renren_id'].') ';		
			}
		}
		if ($at) {		// 如果存在被推荐的人人好友
			$data_renren = new data_renren();
			$url = 'http://uread.me/?ureadmer='.  data_social::make_recommend_id('renren', $article_id);		// 文章链接
			return $data_renren->post($url, $at, $access_token);
		} else return false;
	}
	private function publish_by_kaixin001 ($friends, $access_token, $article_id, $article_title) {
		// 把kaixin001用户都摘出来
		foreach ($friends as $v) {
			if ($v['kaixin001_id'] and $v['kaixin001_actionname']) {
				$kaixin001_friends[] = $v['kaixin001_id'];
			}
		}
		if (is_array($kaixin001_friends)) {
			$data_kaixin001 = new data_kaixin001();
			$msg_header = '推荐：';
			$msg_footer = '';
			$content = $msg_header . $article_title . $msg_footer;
			if (mb_strlen($content) > 140) {
				$content = $msg_header . mb_substr($article_title, 0, (140 - mb_strlen($msg_header) - mb_strlen($msg_footer))) . $msg_footer;
			}
			$link = 'http://uread.me/?ureadmer=' . data_social::make_recommend_id('kaixin001', $article_id);
			foreach ($kaixin001_friends as $v) {
				$at .= '@' . $v . ' ';		// 后面加上一个空格来分隔开
			}
			if ($data_kaixin001->post($access_token, $content, $link, $at)) {
				return true;
			} else return false;
		} else return false;
	}
	private function publish_by_qqwb ($friends, $openid, $access_token, $article_id, $article_title) {
		// 把腾讯用户都摘出来
		foreach ($friends as $v) {
			if ($v['qqwb_id'] and $v['qqwb_actionname']) {
				$qqwb_friends[] = $v['qqwb_actionname'];
			}
		}
		// 如果存在微博好友
		if (is_array($qqwb_friends)) {
			$data_qqwb = new data_qqwb();
			// 构造微博正文
			$msg = array();
			$msg_head = '推荐：《';
			$msg_foot = '》'. $data_qqwb->shorturl($openid, $access_token, 'http://uread.me/?ureadmer='.  data_social::make_recommend_id('qqwb', $article_id)). ' ';
			$tmp = $msg_head . $article_title . $msg_foot;
			// 微博正文的字符别超过140字，如果超过则截短title
			if (mb_strlen($tmp) > 140) {
				$tmp = $msg_head . mb_substr($article_title, 0, (140 - mb_strlen($msg_head) - mb_strlen($msg_foot))) . $msg_foot;
				$msg[0] = $tmp;
				$tmp = '';
			}
			$i = sizeof($msg);
			foreach ($qqwb_friends as $v) {
				$tmp .= '@' . $v;
				if (mb_strlen($tmp) < 140) {		// 长度小于140，把@screen_name真正写入$msg数组中
					$msg[$i]	= $tmp;
				} else {					// 长度超了，那就把tmp清空重写，然后写入到$msg数组的下一个记录中
					$i++;
					$tmp		= '@' . $v;
					$msg[$i]	= $tmp;
				}
				if ($i>2) break;				// 太多的@就忽略了，测试了新浪微博只能评论两次，腾讯微博的能评论多少次不知道，但是太多了也不好。
			}
			// msg的第一条是正文，第2、3条是评论
			if (is_array($msg)) {
				$update = $data_qqwb->post($openid, $access_token, $msg[0]);		// 发布微博
				if ($update['id']) {										// 发布微博成功
					if ($msg[1]) {
						$data_qqwb->comment($openid, $access_token, $update['id'], $msg[1]);	// 只发布两条评论
					}
					if ($msg[2]) {
						$data_qqwb->comment($openid, $access_token, $update['id'], $msg[2]);	// 只发布两条评论
					}
					return true;
				} else return false;
			} else return false;
		} else return false;
	}
	
	public function is_show_extension_tip ($uid) {
		$uid = intval($uid);
		
		if ($uid) {
			$execute = $this->db->execute('
				select
					id
				from
					circle_article
				where
					author_id		= "'.$uid.'"	and
					insite_article_id	= 0
				limit
					1
			');
			if ($execute) {
				return false;
			} else {
				return true;		// 显示extension的提示信息
			}
		}
		return false;
	}
	/**
	 * 修改用户昵称
	 *
	 * @param int $id        	
	 * @param string $nickname
	 *        	没有经过任何转义的
	 * @return int
	 */
	public function edit_nickname ($id, $nickname) {
		$id		= intval($id);
		$nickname	= format_nickname($nickname);
		
		if ($id and $nickname) {
			return $this->db->execute('
                                update
                                        users
                                set
                                        nickname = "' . $nickname . '"
                                where
                                        id	= "' . $id . '"
			');
		} else return false;
	}
	/**
	 * 获取用户自定义的好友昵称，如果不存在，则获取用户本身的昵称
	 *
	 * @param int $uid
	 *        	uid 可以为0
	 * @param int $friend_id        	
	 * @return string
	 */
	public function friend_to_nickname ($uid, $friend_id) {
		$uid = intval($uid);
		$friend_id = intval($friend_id);
		
		if ($friend_id) {
			$execute = $this->db->execute('
                                select
                                        *
                                from
                                        friend
                                where
                                        user_id 	= "' . $uid . '" 		and
                                        friend_id 	= "' . $friend_id . '"
                                limit
                                        1
                        ');
			if ($execute[0]['nickname']) {
				return $execute[0]['nickname'];
			} else {
				$friend = $this->one($friend_id);
				return $friend['nickname'];
			}
		} else return false;
	}
}
?>
